<?php !defined( 'SUNCMS' ) && exit( 'No direct script access allowed'  );

/**
 * 
 * Sun CMS
 * 
 * @author			Burning
 * @copyright		Copyright (c) 2009, IsunCms.Com.
 * @license			http://www.isuncms.com/license.htm
 * @link				http://www.isuncms.com/
 * @since				Version 1.0 Beta
 * 
 */

class Mysql
{
	
	protected static $_conn;						//单态连接

	/**
	 * 构造方法,数据库连接
	 *
	 * @param array $config
	 * 
	 */
	function __construct()
	{
		if( !is_resource( self::$_conn ) )
		{
			self::$_conn = mysql_connect( DB_HOST, DB_USER, DB_PWD );
			mysql_select_db( DB_NAME, self::$_conn );
			mysql_query( "set names " . DB_CHARSET, self::$_conn );
		}
	}
	
	/**
	 * 检查并执行查询
	 *
	 * @param bool $result
	 * @param string $sql
	 */
	private function _check_query( $result, $sql )
	{
		if( !$result )
		{
			show_error("invalid SQL: $sql <br> MySQL Error:", mysql_errno() . mysql_error() );
		}
	}

	/**
	 * 执行SQL并返回结果
	 *
	 * @param string $sql
	 * @return object
	 */
	protected function _sendSQL( $sql )
	{
		$result = mysql_query( $sql, self::$_conn );
		$this->_check_query( $result, $sql );
		return $result;
	}
	
	/**
	 * 数组转化
	 *
	 * @param array $sets
	 * @param string $type
	 * @return string
	 */
	private function _set( $sets, $type = true )
	{
		$whereField = array(); 
		foreach( $sets as $field => $where )
		{
			if( strstr( $where, '>=' ) )
			{
				$whereField[] = "`".$field."` >= '" . strim( str_replace( '>=', '', $where ) )  . "'";
			}
			elseif( strstr( $where, '<=' ) )
			{
				$whereField[] = "`".$field."` <= '" . strim( str_replace( '<=', '', $where ) )  . "'";
			}
			if( strstr( $where, '!=' ) )
			{
				$whereField[] = "`".$field."` != '" . strim( str_replace( '!=', '', $where ) )  . "'";
			}
			elseif( strstr( $where, '>' ) )
			{
				$whereField[] = "`".$field."` > '" . strim( str_replace( '>', '', $where ) ) . "'";
			}
			elseif( strstr( $where, '<' ) )
			{
				$whereField[] = "`".$field."` < '" . strim( str_replace( '<', '', $where ) )  . "'";
			}
			else 
			{
				$whereField[] = "`".$field."` = '" . $where . "'";
			}
		}
		$type = ( $type )?'AND':', ';
		$wheres = implode( $type, $whereField );
		return $wheres;
	}
	
	/**
	 * 数组转化（非查询）
	 *
	 * @param array $sets
	 * @return string
	 */
	private function _set_exec( $sets )
	{
		$datas = array();
		foreach ( $sets as $k => $v )
		{
			$datas["`".$k."`"]  = '"'.$v.'"';
		}
		$keys = array_keys( $datas );
		$values = array_values( $datas );
		$array = array
		(
			'key' => implode( ' , ', $keys ),
			'value' => implode( ' , ', $values )
		);
		return $array;
	}
	
	/**
	 * 插入一条数据
	 *
	 * @param string $table
	 * @param array $data
	 * @return bool
	 */
	function insert( $table, $data )
	{
		$array = $this->_set_exec( $data );
		$sql = "INSERT INTO `".$table."` ( ".$array['key']." ) VALUES ( ".$array['value']." )";
		$result = $this->_sendSQL( $sql );
		return $result;
	}
  	
	/**
	 * 执行自定义非查询sql
	 *
	 * @param string $sql
	 * @return bool
	 */
	function execute( $sql )
	{
		$result = $this->_sendSQL( $sql );
		return $result;
	}
	
	/**
	 * 获取上一步所取得的id
	 *
	 * @return int
	 */
	function insert_id()
	{
		return mysql_insert_id( self::$_conn );
	}
	
	/**
	 * 获取（所有字段）数据
	 *
	 * @param string $table
	 * @param array $limit
	 * @return array
	 */
	function get( $table, $order = array(), $limit = array() )
	{
		$sql = "SELECT * FROM `".$table."`";
		is_array( $order ) && !empty( $order ) && $sql .= ' ORDER BY `'.$order[0].'` '.$order[1];
		is_array( $limit ) && !empty( $limit ) && $sql .= ' LIMIT '.$limit[0].' , '.$limit[1];
		$result = $this->_sendSQL( $sql );
		$datas = array();
		while( $row = mysql_fetch_assoc( $result ) )
		{
			foreach( $row as &$v )
			{
				$v = stripslashes( $v );
			}
			$datas[] = $row;
		}
		return $datas;
	}
	
	/**
	 * 获取一条数据
	 *
	 * @param string $table
	 * @param array $set
	 * @return array
	 */
	function get_one( $table, $set )
	{
		if( empty( $set ) ) return false;
		$wheres = ' WHERE '.$this->_set( $set );
		$sql = "SELECT * FROM ".$table.$wheres;
		$result = $this->_sendSQL( $sql );
		$value = mysql_fetch_assoc( $result );
		return $value;
	}
	
	/**
	 * 获取数据（可以加条件）
	 *
	 * @param string $table
	 * @param array $set
	 * @param array $limit
	 * @return array
	 */
	function get_where( $table, $set, $order = array(), $limit = array() )
	{
		$wheres = ( is_array( $set ) && !empty( $set ) )?' WHERE '.$this->_set( $set ):'';
		$sql = "SELECT * FROM `".$table."` ".$wheres;
		is_array( $order ) && !empty( $order ) && $sql .= ' ORDER BY `'.$order[0].'` '.$order[1];
		is_array( $limit ) && !empty( $limit ) && $sql .= ' LIMIT '.$limit[0].' , '.$limit[1];
		$result = $this->_sendSQL( $sql );
		$datas = array();
		while( $row = mysql_fetch_assoc( $result ) )
		{
			foreach( $row as &$v )
			{
				$v = stripslashes( $v );
			}
			$datas[] = $row;
		}
		return $datas;
	}
	
	/**
	 * 更新数据
	 *
	 * @param string $table
	 * @param array $data
	 * @param array $set
	 * @return bool
	 */
	function update( $table, $data, $set = null )
	{
		if( empty( $data ) ) return false;
		$array = $this->_set( $data, false );
		$wheres = ( is_array( $set ) && !empty( $set ) )?' WHERE '.$this->_set( $set ):'';
		$sql = "UPDATE `".$table."` SET ".$array.$wheres;
		$result = $this->_sendSQL( $sql );
		return $result;
	}
	
	/**
	 * 查询数据表所有数据条数
	 *
	 * @param string $table
	 * @param array $set
	 * @return int
	 */
	function count( $table, $set = null )
	{
		$wheres = ( is_array( $set ) && !empty( $set ) )?' WHERE '.$this->_set( $set ):'';
		$sql = "SELECT COUNT( * ) as count FROM `$table`".$wheres;
		$result = $this->_sendSQL( $sql );
   		$value = mysql_fetch_row( $result );
		return $value[0];
	}
	
	/**
	 * 自定义查询
	 *
	 * @param string $sql
	 * @return array
	 */
	function query( $sql, $return = false )
	{
		$result = $this->_sendSQL( $sql );
		if( !$return )
		{
			$datas = array();
			while( $row = mysql_fetch_assoc( $result ) )
			{
				foreach( $row as &$v )
				{
					$v = stripslashes( $v );
				}
				$datas[] = $row;
			}
		}
		else
		{
			$datas = mysql_fetch_assoc( $result );
		}
		return $datas;
	}
	
	/**
	 * 删除数据
	 *
	 * @param string $table
	 * @param array $set
	 * @return bool
	 */
	function delete( $table, $set )
	{
		$wheres = ( is_array( $set ) && !empty( $set ) )?' WHERE '.$this->_set( $set ):'';
		$sql = "DELETE FROM `".$table."` ".$wheres;
		$result = $this->_sendSQL( $sql );
		return $result;
	}

	/**
	 * 析构函数
	 *
	 */
	function __destruct()
	{
		@mysql_close( self::$_conn );
	}

}